home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Diamond Collection / The Diamond Collection (Software Vault)(Digital Impact).ISO / cdr47 / lzpip103.zip / DISZIP.C < prev    next >
Text File  |  1994-10-30  |  38KB  |  1,052 lines

  1. /* The following is derived from 'funzip' utility sources
  2.  * (funzip.c & inflate.c files) which are written and
  3.  * gracefully put into public domain by Mark Adler.
  4.  * You can find original texts in Info-Zip 'unzip' distribution.
  5.  */
  6.  
  7. /*#define PKZIP_BUG_WORKAROUND*/
  8. #define V100_BUG_WORKAROUND
  9.  
  10. #include <stdio.h>
  11. #include "modern.h"
  12. #include "stdinc.h"
  13. #ifdef MODERN
  14. #  include <string.h>
  15. #else
  16.    char *malloc();
  17. #endif
  18. #include "zipdefs.h"
  19. #include "lzpipe.h"
  20. #include "crc32.h"
  21.  
  22. #ifndef max
  23. #  define max(a,b) (((a) > (b)) ? (a) : (b))
  24. #endif
  25.  
  26. #define AT_EOF 0x80 /* End of data achieved */
  27. #define INITED 0x40 /* Header processed */
  28. #define METHOD 0x03 /* Inflate method mask */
  29. #define IBEGIN 0x20 /* Trees (or stored length) processed */
  30. #define ICFLAG 0x10 /* Copy pending */
  31.  
  32. static uch zipstate = 0;
  33. #ifdef LZFILE
  34.     static FILE *zip_inp_port = NULL;
  35. #       define readbyte() getc(zip_inp_port)
  36. #       define nextbyte() getc(zip_inp_port)
  37. #else
  38.     static int (*zip_inp_port)__ARGS__((void)) = (int(*)())0;
  39. #    define readbyte() (*zip_inp_port)()
  40. #    define nextbyte() (*zip_inp_port)()
  41. #endif
  42.  
  43. #define PF_CRYPT 1 /* PKWare flag fields */
  44. #define PF_ATEOF 8
  45. #define PF_ERROR 0x1ff0
  46.  
  47. #define GF_ASCII   1 /* GNU flag fields */
  48. #define GF_CONT    2
  49. #define GF_EXTRA   4
  50. #define GF_FNAME   8
  51. #define GF_COMMENT 0x10
  52. #define GF_CRYPT   0x20
  53. #define GF_ERROR   0xC0
  54.  
  55. static char ziptype = 0;
  56. static ush zipflags, zmethod;
  57. static ulg crc32val, pkdsize, srcsize;
  58. static uch *slide = (uch*)0;
  59. static ulg outsiz;  /* total bytes written to out */
  60. static char *outbuf;
  61. static ush  outpos; /* output posiztion in slide */
  62.  
  63. /*
  64.    Inflate deflated (PKZIP's method 8 compressed) data.  The compression
  65.    method searches for as much of the current string of bytes (up to a
  66.    length of 258) in the previous 32K bytes.  If it doesn't find any
  67.    matches (of at least length 3), it codes the next byte.  Otherwise, it
  68.    codes the length of the matched string and its distance backwards from
  69.    the current position.  There is a single Huffman code that codes both
  70.    single bytes (called "literals") and match lengths.  A second Huffman
  71.    code codes the distance information, which follows a length code.  Each
  72.    length or distance code actually represents a base value and a number
  73.    of "extra" (sometimes zero) bits to get to add to the base value.  At
  74.    the end of each deflated block is a special end-of-block (EOB) literal/
  75.    length code.  The decoding process is basically: get a literal/length
  76.    code; if EOB then done; if a literal, emit the decoded byte; if a
  77.    length then get the distance and emit the referred-to bytes from the
  78.    sliding window of previously emitted data.
  79.  
  80.    There are (currently) three kinds of inflate blocks: stored, fixed, and
  81.    dynamic.  The compressor outputs a chunk of data at a time, and decides
  82.    which method to use on a chunk-by-chunk basis.  A chunk might typically
  83.    be 32K to 64K, uncompressed.  If the chunk is uncompressible, then the
  84.    "stored" method is used.  In this case, the bytes are simply stored as
  85.    is, eight bits per byte, with none of the above coding.  The bytes are
  86.    preceded by a count, since there is no longer an EOB code.
  87.  
  88.    If the data is compressible, then either the fixed or dynamic methods
  89.    are used.  In the dynamic method, the compressed data is preceded by
  90.    an encoding of the literal/length and distance Huffman codes that are
  91.    to be used to decode this block.  The representation is itself Huffman
  92.    coded, and so is preceded by a description of that code.  These code
  93.    descriptions take up a little space, and so for small blocks, there is
  94.    a predefined set of codes, called the fixed codes.  The fixed method is
  95.    used if the block ends up smaller that way (usually for quite small
  96.    chunks), otherwise the dynamic method is used.  In the latter case, the
  97.    codes are customized to the probabilities in the current block, and so
  98.    can code it much better than the pre-determined fixed codes can.
  99.  
  100.    The Huffman codes themselves are decoded using a mutli-level table
  101.    lookup, in order to maximize the speed of decoding plus the speed of
  102.    building the decoding tables.  See the comments below that precede the
  103.    lbits and dbits tuning parameters.
  104.  */
  105.  
  106. /*
  107.    Notes beyond the 1.93a appnote.txt:
  108.  
  109.    1. Distance pointers never point before the beginning of the output
  110.       stream.
  111.    2. Distance pointers can point back across blocks, up to 32k away.
  112.    3. There is an implied maximum of 7 bits for the bit length table and
  113.       15 bits for the actual data.
  114.    4. If only one code exists, then it is encoded using one bit.  (Zero
  115.       would be more efficient, but perhaps a little confusing.)  If two
  116.       codes exist, they are coded using one bit each (0 and 1).
  117.    5. There is no way of sending zero distance codes--a dummy must be
  118.       sent if there are none.  (History: a pre 2.0 version of PKZIP would
  119.       store blocks with no distance codes, but this was discovered to be
  120.       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
  121.       zero distance codes, which is sent as one code of zero bits in
  122.       length.
  123.    6. There are up to 286 literal/length codes.  Code 256 represents the
  124.       end-of-block.  Note however that the static length tree defines
  125.       288 codes just to fill out the Huffman codes.  Codes 286 and 287
  126.       cannot be used though, since there is no length base or extra bits
  127.       defined for them.  Similarily, there are up to 30 distance codes.
  128.       However, static trees define 32 codes (all 5 bits) to fill out the
  129.       Huffman codes, but the last two had better not show up in the data.
  130.    7. Unzip can check dynamic Huffman blocks for complete code sets.
  131.       The exception is that a single code would not be complete (see #4).
  132.    8. The five bits following the block type is really the number of
  133.       literal codes sent minus 257.
  134.    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
  135.       (1+6+6).  Therefore, to output three times the length, you output
  136.       three codes (1+1+1), whereas to output four times the same length,
  137.       you only need two codes (1+3).  Hmm.
  138.   10. In the tree reconstruction algorithm, Code = Code + Increment
  139.       only if BitLength(i) is not zero.  (Pretty obvious.)
  140.   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
  141.   12. Note: length code 284 can represent 227-258, but length code 285
  142.       really is 258.  The last length deserves its own, short code
  143.       since it gets used a lot in very redundant files.  The length
  144.       258 is special since 258 - 3 (the min match length) is 255.
  145.   13. The literal/length and distance code bit lengths are read as a
  146.       single stream of lengths.  It is possible (and advantageous) for
  147.       a repeat code (16, 17, or 18) to go across the boundary between
  148.       the two sets of lengths.
  149.  */
  150. /* Huffman code lookup table entry--this entry is four bytes for machines
  151.    that have 16-bit pointers (e.g. PC's in the small or medium model).
  152.    Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
  153.    means that v is a literal, 16 < e < 32 means that v is a pointer to
  154.    the next table, which codes e - 16 bits, and lastly e == 99 indicates
  155.    an unused code.  If a code with e == 99 is looked up, this implies an
  156.    error in the data. */
  157.  
  158. #define EOB     15
  159. #define LITERAL 16
  160. #define BAD     99
  161.  
  162. typedef struct _huft {
  163.   uch e; /* number of extra bits or operation */
  164.   uch b; /* number of bits in this code or subcode */
  165.   union {
  166.     ush n; /* literal, length base, or distance base */
  167.     struct _huft *t; /* pointer to next level of table */
  168.   } v;
  169. } huft;
  170.  
  171. /* Function prototypes */
  172. static void huft_free  __ARGS__((huft **));
  173. static int  huft_build __ARGS__((unsigned *, unsigned, unsigned, ush *, ush *,
  174.                                  huft **, int *));
  175. static void copyout __ARGS__((void));
  176. static ush getbits __ARGS__((ush));
  177. static int decode  __ARGS__((unsigned *, huft *, int));
  178. static int inflate_codes __ARGS__((unsigned));
  179. static int inflate_dynamic __ARGS__((unsigned));
  180. static int inflate_fixed   __ARGS__((unsigned));
  181. static int inflate_stored  __ARGS__((unsigned));
  182. static ush getsh __ARGS__((void));
  183. static ulg getlg __ARGS__((void));
  184. static int skip __ARGS__((int));
  185.  
  186. /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
  187.    stream to find repeated byte strings.  This is implemented here as a
  188.    circular buffer.  The index is updated simply by incrementing and then
  189.    and'ing with 0x7fff (32K-1). */
  190. /* It is left to other modules to supply the 32K area.  It is assumed
  191.    to be usable as if it were declared "uch slide[32768];" or as just
  192.    "uch *slide;" and then malloc'ed in the latter case.  The definition
  193.    must be in unzip.h, included above. */
  194. unsigned wp;            /* current position in slide */
  195.  
  196. /* Tables for deflate from PKZIP's appnote.txt. */
  197. static unsigned border[] = {    /* Order of the bit length code lengths */
  198.         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  199. static ush cplens[] = {         /* Copy lengths for literal codes 257..285 */
  200.         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  201.         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  202.         /* note: see note #13 above about the 258 in this list. */
  203. static ush cplext[] = {         /* Extra bits for literal codes 257..285 */
  204.         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  205.         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
  206. static ush cpdist[] = {         /* Copy offsets for distance codes 0..29 */
  207.         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  208.         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  209.         8193, 12289, 16385, 24577};
  210. static ush cpdext[] = {         /* Extra bits for distance codes */
  211.         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  212.         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  213.         12, 12, 13, 13};
  214.  
  215. /* Macros for inflate() bit peeking and grabbing.
  216.    The usage is:
  217.  
  218.         NEEDBITS(j)
  219.         x = b & mask_bits[j];
  220.         DUMPBITS(j)
  221.  
  222.    where NEEDBITS makes sure that b has at least j bits in it, and
  223.    DUMPBITS removes the bits from b.  The macros use the variable k
  224.    for the number of bits in b.  Normally, b and k are register
  225.    variables for speed, and are initialized at the begining of a
  226.    routine that uses these macros from a global bit buffer and count.
  227.  
  228.    If we assume that EOB will be the longest code, then we will never
  229.    ask for bits with NEEDBITS that are beyond the end of the stream.
  230.    So, NEEDBITS should not read any more bytes than are needed to
  231.    meet the request.  Then no bytes need to be "returned" to the buffer
  232.    at the end of the last block.
  233.  
  234.    However, this assumption is not true for fixed blocks--the EOB code
  235.    is 7 bits, but the other literal/length codes can be 8 or 9 bits.
  236.    (The EOB code is shorter than other codes becuase fixed blocks are
  237.    generally short.  So, while a block always has an EOB, many other
  238.    literal/length codes have a significantly lower probability of
  239.    showing up at all.)  However, by making the first table have a
  240.    lookup of seven bits, the EOB code will be found in that first
  241.    lookup, and so will not require that too many bits be pulled from
  242.    the stream.
  243.  */
  244.  
  245. static ulg bb;      /* bit buffer */
  246. static unsigned bk; /* bits in bit buffer */
  247.  
  248. #define NEEDBITS(n) {while(k<(n)){b|=((ulg)nextbyte())<<k;k+=8;}}
  249. #define DUMPBITS(n) {b>>=(n);k-=(n);}
  250. /* A reasonable optimization for 16-bits computers */
  251. #define NEEDTINY(n) {if(k<(n)){b|=(unsigned)nextbyte()<<k;k+=8;}}
  252. #define DUMPTINY(n) {b=(unsigned)b>>(n);k-=(n);}
  253.  
  254. static ush mask_bits[] = {
  255.    0x0000,
  256.    0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
  257.    0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
  258. };
  259.  
  260. /*
  261.    Huffman code decoding is performed using a multi-level table lookup.
  262.    The fastest way to decode is to simply build a lookup table whose
  263.    size is determined by the longest code.  However, the time it takes
  264.    to build this table can also be a factor if the data being decoded
  265.    is not very long.  The most common codes are necessarily the
  266.    shortest codes, so those codes dominate the decoding time, and hence
  267.    the speed.  The idea is you can have a shorter table that decodes the
  268.    shorter, more probable codes, and then point to subsidiary tables for
  269.    the longer codes.  The time it costs to decode the longer codes is
  270.    then traded against the time it takes to make longer tables.
  271.  
  272.    This results of this trade are in the variables lbits and dbits
  273.    below.  lbits is the number of bits the first level table for literal/
  274.    length codes can decode in one step, and dbits is the same thing for
  275.    the distance codes.  Subsequent tables are also less than or equal to
  276.    those sizes.  These values may be adjusted either when all of the
  277.    codes are shorter than that, in which case the longest code length in
  278.    bits is used, or when the shortest code is *longer* than the requested
  279.    table size, in which case the length of the shortest code in bits is
  280.    used.
  281.  
  282.    There are two different values for the two tables, since they code a
  283.    different number of possibilities each.  The literal/length table
  284.    codes 286 possible values, or in a flat code, a little over eight
  285.    bits.  The distance table codes 30 possible values, or a little less
  286.    than five bits, flat.  The optimum values for speed end up being
  287.    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
  288.    The optimum values may differ though from machine to machine, and
  289.    possibly even between compilers.  Your mileage may vary.
  290.  */
  291. #if 0
  292. int lbits = 9; /* bits in base literal/length lookup table */
  293. int dbits = 6; /* bits in base distance lookup table */
  294. #else
  295. #define lbits 9
  296. #define dbits 6
  297. #endif
  298.  
  299. static void huft_free(t)
  300. huft **t; /* table to free */
  301. /* Free the malloc'ed tables built by huft_build(), which makes a linked
  302.    list of the tables it made, with the links in a dummy first entry of
  303.    each table. */
  304. {
  305.    register huft *p, *q;
  306.  
  307.    /* Go through linked list, freeing from the malloced (t[-1]) address. */
  308.    p = *t;
  309.    while (p) {
  310.       q = (--p)->v.t;
  311.       free(p);
  312.       p = q;
  313.    }
  314.    *t = NULL;
  315. }
  316.  
  317. /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
  318. #define BMAX 16   /* maximum bit length of any code (16 for explode) */
  319. #define N_MAX 288 /* maximum number of codes in any set */
  320. #ifdef DEBUG
  321. unsigned hufts;   /* track memory usage */
  322. #endif
  323.  
  324. static int huft_build(b, n, s, d, e, t, m)
  325. unsigned *b; /* code lengths in bits (all assumed <= BMAX) */
  326. unsigned n;  /* number of codes (assumed <= N_MAX) */
  327. unsigned s;  /* number of simple-valued codes (0..s-1) */
  328. ush *d;      /* list of base values for non-simple codes */
  329. ush *e;      /* list of extra bits for non-simple codes */
  330. huft **t;    /* result: starting table */
  331. int *m;      /* maximum lookup bits, returns actual */
  332. /* Given a list of code lengths and a maximum table size, make a set of
  333.    tables to decode that set of codes.  Return zero on success, one if
  334.    the given code set is incomplete (the tables are still built in this
  335.    case), two if the input is invalid (all zero length codes or an
  336.    oversubscribed set of lengths), and three if not enough memory. */
  337. {
  338.   unsigned a;           /* counter for codes of length k */
  339.   unsigned c[BMAX+1];   /* bit length count table */
  340.   unsigned f;           /* i repeats in table every f entries */
  341.   int g;                /* maximum code length */
  342.   int h;                /* table level */
  343.   register unsigned i;  /* counter, current code */
  344.   register unsigned j;  /* counter */
  345.   register int k;       /* number of bits in current code */
  346.   int l;                /* bits per table (returned in m) */
  347.   register unsigned *p; /* pointer into c[], b[], or v[] */
  348.   register huft *q;     /* points to current table */
  349.   huft r;               /* table entry for structure assignment */
  350.   huft *u[BMAX];        /* table stack */
  351.   unsigned v[N_MAX];    /* values in order of bit length */
  352.   register int w;       /* bits before this table == (l * h) */
  353.   unsigned x[BMAX+1];   /* bit offsets, then code stack */
  354.   unsigned *xp;         /* pointer into x */
  355.   int y;                /* number of dummy codes added */
  356.   unsigned z;           /* number of entries in current table */
  357.  
  358.   /* Generate counts for each bit length */
  359.   for (i=0; i<=BMAX; i++) c[i] = 0;
  360.   p = b;  i = n;
  361.   do {
  362.     c[*p++]++;     /* assume all entries <= BMAX */
  363.   } while (--i);
  364.   if (c[0] == n) { /* null input--all zero length codes */
  365.     *t = (huft *)NULL;
  366.     *m = 0;
  367.     return 0;
  368.   }
  369.  
  370.   /* Find minimum and maximum length, bound *m by those */
  371.   l = *m;
  372.   for (j = 1; j <= BMAX && !c[j]; j++);
  373.   k = j; /* minimum code length */
  374.   if ((unsigned)l < j) l = j;
  375.   for (i = BMAX; i && !c[i]; i--);
  376.   g = i; /* maximum code length */
  377.   if ((unsigned)l > i) l = i;
  378.   *m = l;
  379.  
  380.   /* Adjust last length count to fill out codes, if needed */
  381.   for (y = 1 << j; j < i; j++, y <<= 1)
  382.     if ((y -= c[j]) < 0) return 2; /* bad input: more codes than bits */
  383.   if ((y -= c[i]) < 0) return 2;
  384.   c[i] += y;
  385.  
  386.   /* Generate starting offsets into the value table for each length */
  387.   x[1] = j = 0;
  388.   p = c + 1;  xp = x + 2;
  389.   while (--i) {                 /* note that i == g from above */
  390.     *xp++ = (j += *p++);
  391.   }
  392.  
  393.   /* Make a table of values in order of bit lengths */
  394.   p = b;  i = 0;
  395.   do {
  396.     if ((j = *p++) != 0) v[x[j]++] = i;
  397.   } while (++i < n);
  398.  
  399.   /* Generate the Huffman codes and for each, make the table entries */
  400.   x[0] = i = 0;        /* first Huffman code is zero */
  401.   p = v;               /* grab values in bit order */
  402.   h = -1;              /* no tables yet--level -1 */
  403.   w = -l;              /* bits decoded == (l * h) */
  404.   u[0] = (huft *)NULL; /* just to keep compilers happy */
  405.   q = (huft *)NULL;    /* ditto */
  406.   z = 0;               /* ditto */
  407.  
  408.   /* go through the bit lengths (k already is bits in shortest code) */
  409.   for (; k <= g; k++) {
  410.     a = c[k];
  411.     while (a--) {
  412.       /* here i is the Huffman code of length k bits for value *p */
  413.       /* make tables up to required level */
  414.       while (k > w + l) {
  415.         h++;
  416.         w += l;                 /* previous table always l bits */
  417.  
  418.         /* compute minimum size table less than or equal to l bits */
  419.         z = (z = g - w) > (unsigned)l ? l : z;  /* upper limit on table size */
  420.         if ((f = 1 << (j = k - w)) > a + 1) {   /* try a k-w bit table */
  421.           f -= a + 1;           /* too few codes for k-w bit table */
  422.           xp = c + k;           /* deduct codes from patterns left */
  423.           while (++j < z) {     /* try smaller tables up to z bits */
  424.             if ((f <<= 1) <= *++xp)
  425.               break;            /* enough codes to use up j bits */
  426.             f -= *xp;           /* else deduct codes from patterns */
  427.           }
  428.         }
  429.         z = 1 << j;             /* table entries for j-bit table */
  430.  
  431.         /* allocate and link in new table */
  432.         q = (huft *)malloc((z + 1)*sizeof(huft));
  433.         if (!q) {/* not enough memory */
  434.           if (h) huft_free(u); return (lzerror=ZNOMEM, ERROR);
  435.         }
  436. #ifdef DEBUG
  437.         hufts += z + 1;         /* track memory usage */
  438. #endif
  439.         *t = q + 1;             /* link to list for huft_free() */
  440.         *(t = &(q->v.t)) = (huft *)NULL;
  441.         u[h] = ++q;             /* table starts after link */
  442.  
  443.         /* connect to last table, if there is one */
  444.         if (h) {
  445.           x[h] = i;             /* save pattern for backing up */
  446.           r.b = (uch)l;         /* bits to dump before this table */
  447.           r.e = (uch)(16 + j);  /* bits in this table */
  448.           r.v.t = q;            /* pointer to this table */
  449.           j = i >> (w - l);     /* (get around Turbo C bug) */
  450.           u[h-1][j] = r;        /* connect to last table */
  451.         }
  452.       }
  453.  
  454.       /* set up table entry in r */
  455.       r.b = (uch)(k - w);
  456.       if (p >= v + n) {
  457.         r.e = 99;               /* out of values--invalid code */
  458.       } else if (*p < s) {
  459.         r.e = (uch)(*p < 256 ? 16 : 15);    /* 256 is end-of-block code */
  460.         r.v.n = *p++;           /* simple code is just the value */
  461.       } else {
  462.         r.e = (uch)e[*p - s];   /* non-simple--look up in lists */
  463.         r.v.n = d[*p++ - s];
  464.       }
  465.  
  466.       /* fill code-like entries with r */
  467.       f = 1 << (k - w);
  468.       for (j = i >> w; j < z; j += f) q[j] = r;
  469.  
  470.       /* backwards increment the k-bit code i */
  471.       for (j = 1 << (k - 1); i & j; j >>= 1) i ^= j;
  472.       i ^= j;
  473.  
  474.       /* backup over finished tables */
  475.       while ((i & ((1 << w) - 1)) != x[h]) {
  476.         h--; /* don't need to update q */
  477.         w -= l;
  478.       }
  479.     }
  480.   }
  481.   /* Return true (1) if we were given an incomplete table */
  482.   return y != 0 && g != 1;
  483. }
  484.  
  485. static void copyout()
  486. {
  487.    register unsigned length;
  488.  
  489.    if ((length = wp - outpos) != 0) {
  490.       updcrc(slide+outpos, length);
  491. #ifdef NOMEMCPY
  492.       while (length--) *outbuf++ = (char)slide[outpos++];
  493. #else
  494.       (void)memcpy(outbuf, slide+outpos, length);
  495.       outbuf += length;
  496.       outpos += length;
  497. #endif
  498.       outsiz += length;
  499.    }
  500. }
  501.  
  502. static ush getbits(n)
  503. ush n; /* number of bits to get */
  504. {
  505.    register ulg b;      /* bit buffer */
  506.    register unsigned k; /* number of bits in bit buffer */
  507.    register unsigned j;
  508.  
  509.    /* make local copies of globals */
  510.    b = bb; k = bk;
  511.    NEEDBITS(n);
  512.    j = (unsigned)b & mask_bits[n];
  513.    DUMPBITS(n);
  514.    /* restore the globals from the locals */
  515.    bk = k; bb = b;
  516.    return j;
  517. }
  518.  
  519. static int decode(np, t, bn)
  520. unsigned *np; /* decoded value */
  521. huft *t;      /* tree to decode */
  522. int bn;       /* bits number */
  523. /* Returns number of extra bits (BAD on error). */
  524. {
  525.    register ulg b;      /* bit buffer */
  526.    register unsigned k; /* number of bits in bit buffer */
  527.  
  528.    /* make local copies of globals */
  529.    b = bb; k = bk;
  530.    for (;;) {
  531.       NEEDBITS((unsigned)bn)
  532.       t += ((unsigned)b & mask_bits[bn]);
  533.       if ((bn = t->e) == BAD) goto end;
  534.       DUMPBITS(t->b)
  535.       if (bn <= 16) break;
  536.       t = t->v.t;
  537.       bn -= 16;
  538.    }
  539.    *np = t->v.n;
  540.    /* restore the globals from the locals */
  541.    bk = k; bb = b;
  542. end:
  543.    return bn;
  544. }
  545.  
  546. static huft *tl = NULL; /* literal/length code table */
  547. static huft *td = NULL; /* distance code table */
  548. static int bl;          /* lookup bits for tl */
  549. static int bd;          /* lookup bits for td */
  550.  
  551. static int inflate_codes(length)
  552. unsigned length;
  553. /* inflate (decompress) the codes in a deflated (compressed) block.
  554.    Return an number of bytes decompressed or ERROR. */
  555. {
  556.    register unsigned i;
  557.    register unsigned e; /* number of extra bits */
  558.    static unsigned n,d; /* length and index for copy */
  559.  
  560.    for (i=0; i<length;) {
  561.       if (!(zipstate & ICFLAG)) {
  562.          if ((e = decode(&n, tl, bl)) == BAD)
  563.             return (lzerror=ZMOULD, ERROR);
  564.          if (e == LITERAL) {
  565.             slide[wp++] = (uch)n;
  566.             if (wp >= WSIZE) {
  567.                copyout(); outpos = wp = 0;
  568.             }
  569.             ++i;
  570.             continue;
  571.          }
  572.          if (e == EOB) {
  573.             /* clear all unneccesary flags & exit */
  574.             zipstate &= AT_EOF|INITED; break;
  575.          }
  576.          /* Length code encountered, get length of block to copy */
  577.          n += getbits(e);
  578.          /* decode distance of block to copy */
  579.          if ((e = decode(&d, td, bd)) == BAD)
  580.             return (lzerror=ZMOULD, ERROR);
  581.          d = wp - (d + getbits(e));
  582.       }
  583.       zipstate &= ~ICFLAG;
  584.       /* do the copy */
  585.       do {
  586.          d &= WSIZE-1;
  587.          if ((e = WSIZE - max(d,wp)) > n) e = n;
  588.          if (i+e > length) {
  589.             zipstate |= ICFLAG; e = length-i;
  590.          }
  591.          i += e;
  592.          n -= e;
  593. #ifndef NOMEMCPY
  594.          if (wp - d >= e) {/* (this test assumes unsigned comparison) */
  595.             memcpy(slide + wp, slide + d, e);
  596.             wp += e;
  597.             d += e;
  598.          } else /* do it slow to avoid memcpy() overlap */
  599. #endif /* !NOMEMCPY */
  600.             do slide[wp++] = slide[d++]; while (--e);
  601.          if (wp >= WSIZE) {
  602.             copyout(); outpos = wp  = 0;
  603.          }
  604.       } while (n && !(zipstate & ICFLAG));
  605.    }
  606.    copyout();
  607.    return i;
  608. }
  609.  
  610. static int inflate_dynamic(length)
  611. unsigned length;
  612. /* decompress an inflated type 2 (dynamic Huffman codes) block. */
  613. /* Returns number of bytes decompressed or ERROR. */
  614. {
  615.    register i;
  616.  
  617.    if (!(zipstate & IBEGIN)) {
  618.       unsigned j;
  619.       unsigned l;  /* last length */
  620.       unsigned m;  /* mask for bit lengths table */
  621.       unsigned n;  /* number of lengths to get */
  622.       unsigned nb; /* number of bit length codes */
  623.       unsigned nl; /* number of literal/length codes */
  624.       unsigned nd; /* number of distance codes */
  625. #ifdef PKZIP_BUG_WORKAROUND
  626.       unsigned ll[288+32]; /* literal/length and distance code lengths */
  627. #else
  628.       unsigned ll[286+30]; /* literal/length and distance code lengths */
  629. #endif
  630.       register ulg b;      /* bit buffer */
  631.       register unsigned k; /* number of bits in bit buffer */
  632.  
  633.       /* make local bit buffer */ b = bb; k = bk;
  634.  
  635.       /* read in table lengths */
  636.       NEEDTINY(5)
  637.       nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */
  638.       DUMPTINY(5)
  639.       NEEDTINY(5)
  640.       nd = 1 + ((unsigned)b & 0x1f);   /* number of distance codes */
  641.       DUMPTINY(5)
  642.       NEEDTINY(4)
  643.       nb = 4 + ((unsigned)b & 0xf);    /* number of bit length codes */
  644.       DUMPTINY(4)
  645. #ifdef PKZIP_BUG_WORKAROUND
  646.       if (nl > 288 || nd > 32)
  647. #else
  648.       if (nl > 286 || nd > 30)
  649. #endif
  650.         return (lzerror=ZMOULD, ERROR); /* bad lengths */
  651.  
  652.       /* read in bit-length-code lengths */
  653.       for (j = 0; j < nb; j++) {
  654.         NEEDTINY(3)
  655.         ll[border[j]] = (unsigned)b & 7;
  656.         DUMPTINY(3)
  657.       }
  658.       for (; j < 19; j++) ll[border[j]] = 0;
  659.  
  660.       /* build decoding table for trees--single level, 7 bit lookup */
  661.       bl = 7;
  662.       if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
  663.          if (i != ERROR) /* all save memory lack */ lzerror = ZMOULD;
  664.          if (i == TRUE) /* incomplete code set */ huft_free(&tl);
  665.          return ERROR;
  666.       }
  667.  
  668.       /* read in literal and distance code lengths */
  669.       n = nl + nd;
  670.       m = mask_bits[bl];
  671.       i = l = 0;
  672.       while ((unsigned)i < n) {
  673.         NEEDBITS((unsigned)bl)
  674.         j = (td = tl + ((unsigned)b & m))->b;
  675.         DUMPBITS(j)
  676.         j = td->v.n;
  677.         if (j < 16) {      /* length of code in bits (0..15) */
  678.           ll[i++] = l = j; /* save last length in l */
  679.         } else {
  680.           if (j == 16) {/* repeat last length 3 to 6 times */
  681.             NEEDTINY(2)
  682.             j = 3 + ((unsigned)b & 3);
  683.             DUMPTINY(2)
  684.           } else {
  685.             l = 0;
  686.             if (j == 17) {/* 3 to 10 zero length codes */
  687.               NEEDTINY(3)
  688.               j = 3 + ((unsigned)b & 7);
  689.               DUMPTINY(3)
  690.             } else {/* j == 18: 11 to 138 zero length codes */
  691.               NEEDTINY(7)
  692.               j = 11 + ((unsigned)b & 0x7f);
  693.               DUMPTINY(7)
  694.             }
  695.           }
  696.           if ((unsigned)i + j > n) return (lzerror=ZMOULD, ERROR);
  697.           while (j--) ll[i++] = l;
  698.         }
  699.       }
  700.  
  701.       /* free decoding table for trees */
  702.       huft_free(&tl);
  703.  
  704.       /* restore the global bit buffer */
  705.       bb = b;
  706.       bk = k;
  707.  
  708.       /* build the decoding tables for literal/length and distance codes */
  709.       bl = lbits;
  710.       if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
  711.          if (i != ERROR) /* all save memory lack */ lzerror = ZMOULD;
  712.          if (i == TRUE) /* incomplete literal tree */ huft_free(&tl);
  713.          return ERROR;
  714.       }
  715.       bd = dbits;
  716.       if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
  717. #ifndef PKZIP_BUG_WORKAROUND
  718.          if (i == TRUE) huft_free(&td); /* incomplete distance tree */
  719. #else
  720.          if (i != TRUE)
  721. #endif
  722.          {
  723.             huft_free(&tl);
  724.             if (i != ERROR) lzerror = ZMOULD;
  725.             return ERROR;
  726.          }
  727.       }
  728.       zipstate |= IBEGIN;
  729.    }
  730.    if ((i = inflate_codes(length)) == ERROR || !(zipstate & IBEGIN)) {
  731.       huft_free(&tl); huft_free(&td);
  732.    }
  733.    return i;
  734. }
  735.  
  736. static int inflate_fixed(length)
  737. unsigned length;
  738. /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
  739.    either replace this with a custom decoder, or at least precompute the
  740.    Huffman tables. */
  741. /* Returns number of bytes decompressed or ERROR. */
  742. {
  743.    register i;
  744.  
  745.    if (!(zipstate & IBEGIN)) {
  746.       unsigned l[288]; /* length list for huft_build */
  747.  
  748.       i = 0;
  749.       /* set up literal table; make a complete, but wrong code set */
  750.       do l[i] = 8; while (++i < 144);
  751.       do l[i] = 9; while (++i < 256);
  752.       do l[i] = 7; while (++i < 280);
  753.       do l[i] = 8; while (++i < 288);
  754.  
  755.       bl = 7;
  756.       if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0) {
  757.          if (i != ERROR) /* all save memory lack */ lzerror = ZERROR;
  758.          if (i == TRUE) /* incomplete code set */ huft_free(&tl);
  759.          return ERROR;
  760.       }
  761.  
  762.       /* set up distance table */
  763.       for (i=0; i<30; i++) l[i] = 5; /* make an incomplete code set */
  764.  
  765.       bd = 5;
  766.       if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) & ~1) {
  767.          if (i != ERROR) lzerror = ZERROR;
  768.          huft_free(&tl);
  769.          return ERROR;
  770.       }
  771.       zipstate |= IBEGIN;
  772.    }
  773.    if ((i = inflate_codes(length)) == ERROR || !(zipstate & IBEGIN)) {
  774.       huft_free(&tl); huft_free(&td);
  775.    }
  776.    return i;
  777. }
  778.  
  779. static int inflate_stored(length)
  780. unsigned length;
  781. /* "decompress" an inflated type 0 (stored) block. */
  782. /* Returns number of bytes restored or ERROR. */
  783. {
  784.    static unsigned n; /* number of bytes to copy */
  785.    register unsigned i;
  786.  
  787.    if (!(zipstate & IBEGIN)) {
  788.       if (bk > 7) /* fail to align bit buffer */
  789.          return (lzerror=ZERROR, ERROR);
  790.       /* go to byte boundary */
  791.       bb = 0; /* bit buffer */
  792.       bk = 0; /* number of bits in bit buffer */
  793.  
  794.       /* get the length and its complement */
  795.       n = nextbyte(); n |= nextbyte() << 8;
  796.       i = nextbyte(); i |= nextbyte() << 8;
  797.       if (n != (i ^ 0xffff)) /* data error */
  798.          return (lzerror=ZMOULD, ERROR);
  799.       zipstate |= IBEGIN;
  800.    }
  801.    /* read and output the "compressed" data */
  802.    for (i=0; i<length; i++) {
  803.       if (n-- == 0) {
  804.          /* End of block - clear method and other unneccesary flags */
  805.          zipstate &= AT_EOF|INITED;
  806.          break;
  807.       }
  808.       slide[wp++] = (uch)nextbyte();
  809.       if (wp >= WSIZE) {
  810.          copyout(); outpos = wp = 0;
  811.       }
  812.    }
  813.    copyout();
  814.    return i;
  815. }
  816.  
  817. static int skip(n)
  818. register int n;
  819. {
  820.    while (n--) if (readbyte()==EOF) return EOF; return 0;
  821. }
  822.  
  823. static ush getsh()
  824. {
  825.    register ush i; i = readbyte(); return i | (readbyte() << 8);
  826. }
  827.  
  828. static ulg getlg()
  829. {
  830.    register ush i = 0;
  831.    register ulg l = 0;
  832.  
  833.    if (bk) {
  834.       i = bk & ~7;
  835.       l = bb >> (bk & 7);
  836.       bb = 0;
  837.       bk = 0;
  838.    }
  839.    for (; i<32; i+=8) l |= (ulg)readbyte() << i;
  840.    return l;
  841. }
  842.  
  843. int unzalloc()
  844. {
  845.    if (!slide) slide = (uch*)malloc(WSIZE); return !slide;
  846. }
  847.  
  848. int unzopen(inp_port, ztype)
  849. #ifdef LZFILE
  850.     FILE *inp_port;
  851. #else
  852.     int (*inp_port)__ARGS__((void));
  853. #endif
  854. int ztype;
  855. {
  856.    lzerror = 0;
  857.    if (unzalloc()) return (lzerror = ZNOMEM);
  858.    zip_inp_port = inp_port;
  859.    zipstate = 0;
  860.    ziptype = ztype;
  861.    outsiz = 0L;
  862.    /* Initialise CRC calculations */
  863.    crcbegin();
  864.    /* Initialise deflate */
  865.    wp = 0; bb = 0; bk = 0;
  866.    outpos = 0;
  867.    return 0;
  868. }
  869.  
  870. int unzread(buffer, length)
  871. char *buffer; unsigned length;
  872. {
  873.    register i;
  874.    register unsigned j, k;
  875.    register ulg b;
  876.  
  877.    if (!(zipstate & INITED)) {/* Read and decode header */
  878.       if (!slide || !zip_inp_port) return (lzerror = ZNOPEN, ERROR);
  879.  
  880.       /* Check for zip type */
  881.       k = getsh();
  882.       if        (ziptype == ZIP_GNU) {
  883.          if (k != GZIP_MAGIC) return ZMAGIC;
  884.       } else if (ziptype == ZIP_PKW) {
  885.          if (k!=PKW_01_MAGIC || getsh()!=PKW_23_MAGIC) return ZMAGIC;
  886.       } else {
  887.          if (k==PKW_01_MAGIC && getsh()==PKW_23_MAGIC) ziptype=ZIP_PKW;
  888.          else if (k == GZIP_MAGIC)                     ziptype=ZIP_GNU;
  889.          else return ZMAGIC;
  890.       }
  891.       /* Decode header */
  892.       if (ziptype == ZIP_GNU) {
  893.          zmethod  = readbyte();
  894.          if ((zipflags = readbyte()) & (GF_ERROR|GF_CRYPT|GF_CONT))
  895.             return ZUNSUP;
  896.          /* Skip file time, extra flags and OS type */
  897.          if (skip(6)) return ZHDEOF;
  898. #if 0
  899.          if (zipflags & GF_CONT) {
  900.             /* Skip the part number */ if (skip(2)) return ZHDEOF;
  901.          }
  902. #endif
  903.          if (zipflags & GF_EXTRA) {/* Skip the extra field */
  904.             k = getsh(); if (skip(k)) return ZHDEOF;
  905.          }
  906.          if (zipflags & GF_FNAME) {/* Skip the file name */
  907.             do if ((i=readbyte()) == EOF) return ZHDEOF; while (i);
  908.          }
  909.          if (zipflags & GF_COMMENT) {/* Skip comment */
  910.             do if ((i=readbyte()) == EOF) return ZHDEOF; while (i);
  911.          }
  912.       } else {/* PKWARE */
  913.          if (skip(2)) return ZHDEOF; /* version to extract */
  914.          if ((zipflags = getsh()) & (PF_ERROR|PF_CRYPT)) return ZUNSUP;
  915.          zmethod  = getsh();
  916.          if (skip(4)) return ZHDEOF; /* skip file time/date */
  917.          crc32val = getlg();
  918.          pkdsize  = getlg();
  919.          srcsize  = getlg();
  920.          k = getsh(); /* file name length */
  921.          j = getsh(); /* extra field length */
  922.          if (/* header length */30L + k + j > 65535L || skip(k+j))
  923.             return ZHDEOF;
  924.       }
  925.       /* Header decoded */
  926.       zipstate |= INITED;
  927.    }
  928.    if (zmethod == DEFLATED) {
  929.       outbuf = buffer;
  930.       j = 0;
  931.       do {
  932.          if (!(zipstate & METHOD)) {
  933.             if (zipstate & AT_EOF) break;
  934.  
  935.             /* make local bit buffer */
  936.             b = bb; k = bk;
  937.  
  938.             /* read in last block bit */
  939.             NEEDTINY(1)
  940.             if ((int)b & 1) zipstate |= AT_EOF;
  941.             DUMPTINY(1)
  942.  
  943.             /* read in block type */
  944.             NEEDTINY(2)
  945.             if ((i = ((int)b & 3) + 1) & ~METHOD)
  946.                return (lzerror=ZMOULD, ERROR);
  947.             DUMPTINY(2)
  948.             zipstate |= i;
  949.  
  950.             /* restore the global bit buffer */
  951.             bb = b; bk = k;
  952.          }
  953.          k = length - j;
  954.          switch (zipstate & METHOD) {
  955.             case 3 : i = inflate_dynamic(k); break;
  956.             case 2 : i = inflate_fixed  (k); break;
  957.             case 1 : i = inflate_stored (k); break;
  958.             default: lzerror = ZMOULD; return ERROR;
  959.          }
  960.          if (i == ERROR) return i;
  961.       } while ((i || !(zipstate & AT_EOF)) && (j+=i) < length);
  962.       return j;
  963.    } else if (ziptype == ZIP_PKW && zmethod == STORED) {
  964.       zipstate |= 1; /* Dummy 'stored' flag */
  965.       k = length > pkdsize ? (unsigned)pkdsize : length;
  966.       for (j=0; j<k && (i=readbyte())!=EOF; j++) buffer[j] = i;
  967.       if (j) {
  968.          pkdsize -= j;
  969.          updcrc((unsigned char*)buffer, j);
  970.          outsiz += j;
  971.       }
  972.       if (!pkdsize) {
  973.          zipstate &= ~METHOD; zipstate |= AT_EOF;
  974.       }
  975.       return i == EOF ? (lzerror=ZMOULD, ERROR) : j;
  976.    }
  977.    lzerror = ZUNSUP;
  978.    return ERROR;
  979. }
  980.  
  981. void unzfree()
  982. {
  983.    if (slide) { free(slide); slide = (uch*)0; }
  984.    if (tl) huft_free(&tl);
  985.    if (td) huft_free(&td);
  986. }
  987.  
  988. int unzclose()
  989. {
  990.    int k = ERROR;  /* return value */
  991.    int i = 0;      /* bytes rest */
  992.    register ulg l; /* working variable */
  993.  
  994.    lzerror = ZNOPEN;
  995.    if (!slide || !zip_inp_port || !(zipstate & INITED)) goto end;
  996.  
  997.    if (!(zipstate & AT_EOF)) {
  998.       /* Indicate warning message */ k = (lzerror=ZNOEOF); goto end;
  999.    }
  1000.    if (zipstate & METHOD) {
  1001.       char b[16]; register j;
  1002.       /* skip the rest of data */
  1003.       while ((j=unzread(b, sizeof(b))) == sizeof(b)) i += j;
  1004.       if (j == ERROR) goto end;
  1005.    }
  1006.    if        (ziptype == ZIP_GNU) {
  1007.       crc32val = getlg();
  1008.       srcsize  = getlg();
  1009.    } else if (ziptype == ZIP_PKW) {
  1010.       if (zipflags & PF_ATEOF) {
  1011. #ifdef V100_BUG_WORKAROUND
  1012.          if ((l = getlg()) == PKW_EXT) {
  1013.             if ((crc32val = getlg()) == getcrc()) {
  1014.                (void)    getlg(); /* Skip the packed size */
  1015.                srcsize = getlg();
  1016.                goto crc_ok;
  1017.             }
  1018.          } else {
  1019.             (void)getlg(); /* Skip the packed size */
  1020.          }
  1021.          crc32val = l;
  1022. #else
  1023.          if (getlg() != PKW_EXT) { lzerror = ZMOULD; goto end; }
  1024.          crc32val = getlg();
  1025.          (void)     getlg(); /* Ignore packed size */
  1026. #endif
  1027.          srcsize  = getlg();
  1028.       }
  1029.    } else {
  1030.       lzerror = ZNOPEN; goto end;
  1031.    }
  1032.    if (crc32val != getcrc()) { lzerror = BADCRC; goto end; }
  1033. crc_ok:
  1034.    if (outsiz   !=  srcsize) { lzerror = ZBADSZ; goto end; }
  1035.  
  1036.    if (ziptype == ZIP_PKW) {
  1037.       /* Test for the end of archive */
  1038.       if ((l = getlg()) != PKW_CENTRAL) {
  1039.          /* Indicate warning message */
  1040.          k = (lzerror = l==PKW_LOCAL ? ZNOEOF : ZMOULD);
  1041.          goto end;
  1042.       }
  1043.    }
  1044.    k = 0; /* Indicate normal close */
  1045.    if (i) k = (lzerror = ZNOEOF);
  1046. end:
  1047.    unzfree();
  1048.    zipstate = 0;
  1049.    zip_inp_port = NULL;
  1050.    return k;
  1051. }
  1052.